!(function () {
  window.LCache={
    cacheMap:{},//缓存的url
    curMap:{},//当前的url
    loadChunk:loadChunk,
    version:'1.0.3',
    useCache:true,
    storagePrefix:'LCache-',//前缀
    loadAll:function (arrUrl,callback) {
      if(typeof arrUrl==='string'){arrUrl=[arrUrl]}
      var arr=[];
      for(var i=0;i<arrUrl.length;i++){
        var key=arrUrl[i];
        if(key&&!this.curMap[getFileKey(key)]){
          arr.push(key)
        }
      }
      loadAll(arr,callback);
    }
  }
  //ajax获取文本
  function getText(url,callback) {
    var xmlhttp=new XMLHttpRequest();
    if(typeof callback!=='function'){
      xmlhttp.open("GET",url,false);
      xmlhttp.send();
      return xmlhttp.responseText;
    }
    xmlhttp.onreadystatechange=function () {
      if (this.readyState===4&&this.status===200){
        callback(this.responseText)
      }
    };
    xmlhttp.open("GET",url,true);
    xmlhttp.send();
  }
  //获取文件key
  function getFileKey(url) {
    return url.replace(/(?!\w+)\.\w+\.(js|css)/,'.$1').replace(/\?.+/,'')
  }
  var UpLCacheLib=localStorage.getItem('UpLCacheLib')||'';
  LCache.curMap[getFileKey(UpLCacheLib)]=UpLCacheLib;
  LCache.cacheMap[getFileKey(UpLCacheLib)]=UpLCacheLib;
  if(LCache.version!==localStorage.getItem('LCacheVersion')){
    localStorage.setItem('LCacheVersion',LCache.version)
    LCache.useCache=false;
  }

  //获取缓存的url
  for (var i = 0; i < localStorage.length; i++) {
    var key = localStorage.key(i);
    if(key.indexOf(LCache.storagePrefix)===0){
      if(UpLCacheLib&&getFileKey(UpLCacheLib)===getFileKey(key)&&UpLCacheLib!==key){
        localStorage.removeItem(key);
      }else{
        if(LCache.useCache){
          LCache.cacheMap[getFileKey(key)]=key;
        }else{
          localStorage.removeItem(key);
        }
      }
    }
  }

  //渲染js、css
  var head = typeof document!='undefined'&&document.getElementsByTagName('head')[0];
  function exec(item){
    if(/\.css/.test(item.url)){
      var s = document.createElement("style");
      s.setAttribute('data-href',item.url)
      s.innerHTML = item.text;
      head.appendChild(s)
    }else if(/\.js/.test(item.url)){
      var script = document.createElement('script');
      script.text = item.text;
      head.appendChild( script );
    }
  }
  //清除缓存
  function clearCache(key,text) {
    if(key&&text){
      console.log('clearCache')
      for(var nkey in LCache.cacheMap){
        if(!LCache.curMap[nkey]||LCache.curMap[nkey]!==LCache.cacheMap[nkey]){
          localStorage.removeItem(LCache.cacheMap[nkey]);
        }
      }
      try {
        localStorage.setItem(key,text);
      }catch (e) {
        clearCache()
      }
    }else{
      console.log('clearAllPreCache')
      for(var key in LCache.cacheMap){
        localStorage.removeItem(LCache.cacheMap[key]);
      }

    }
  }
  function loadItem(url,i,callback) {
    var key=LCache.storagePrefix+url;
    var preKey=LCache.cacheMap[getFileKey(key)]
    //url版本不一致
    if(!preKey||key!==preKey){
      getText(url,function (text) {
        //删除旧版本
        localStorage.removeItem(preKey);
        //添加新版本
        try {
          localStorage.setItem(key,text);
        }catch (e) {
          clearCache(key,text);
        }finally {
          callback({
            url:url,
            text:text
          },i)
        }
      })
    }else{
      callback({
        url:url,
        text:localStorage.getItem(key)
      },i)
    }
  }

  //异步并发加载，同步执行
  function loadAll(arr,callback){

    var data=[];
    var cur=-1;
    for(var i=0;i<arr.length;i++){
      var url=arr[i];
      var key=LCache.storagePrefix+url;
      LCache.curMap[getFileKey(key)]=key;
      loadItem(url,i,function (item,i) {
        data[i]=item;
        if(i-cur==1){
          synchro(i)
        }
      })
    }
    //同步执行
    function synchro(i){
      if(i<arr.length){
        if(data[i]){
          cur=i;
          exec(data[i]);
          synchro(i+1)
        }
      }else{
        callback&&callback()
      }
    }
  }
//执行增量包
  function execChunk(s1,chunk){
    var ns='';
    for(var i=0;i<chunk.length;i++){
      var arr=chunk[i];
      if(Object.prototype.toString.call(arr)==='[object Array]'){
        ns=ns+s1.substr(arr[0],arr[1])
      }else{
        ns=ns+arr
      }
    }
    return ns;
  }

  //加载增量包
  function loadChunk(curVersion,name) {
    var chunkVersion=localStorage.getItem(name);
    localStorage.setItem(name,curVersion);
    if(LCache.useCache&&chunkVersion&&chunkVersion!==curVersion){
      try {
        var text=getText('chunk/'+chunkVersion+'-'+curVersion+'.json')
        var chunkArr=JSON.parse(text);

        for(var i=0;i<chunkArr.length;i++){
          var obj=chunkArr[i]
          var preKey=LCache.storagePrefix+obj.a;
          var key=LCache.storagePrefix+obj.b;
          var s1=localStorage.getItem(preKey);

          if(s1){
            var s2=execChunk(s1,obj.c);
            LCache.cacheMap[getFileKey(preKey)]=key;
            localStorage.removeItem(preKey);
            localStorage.setItem(key,s2);
          }
        }
      }catch (e) {

      }
    }

  }

})()
